using System;
using System.Web.Mvc;
using System.Web.Profile;
using System.Web.Routing;
using System.Web.Security;
using Core.BOL;
using Core.DAL;
using Core.Utils;
using ScoutNET.Attributes;

namespace ScoutNET.Controllers
{
    public class ContactController : ApplicationController
    {
        private SectionRepository sr = new SectionRepository();

        #region Views
        public ActionResult Index(string systemName)
        {
            tSite_Section section = null;
            string sName = string.Empty;
            if (systemName != null)
            {
                section = sr.GetSectionsBySystemName(systemName);
                if (section != null)
                {
                    sName = section.Section;
                }
            }

            ViewData["PageDescription"] = Resources.Contact_Index_Description.Replace("[SECTION]", sName.ToLower());
            ViewData["PageTitle"] = Resources.Contact_Index_Title.Replace("[SECTION]", sName.ToLower());

            string[] saBreadcrumb = new String[2];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = Resources.Contact_Index_Breadcrumb.Replace("[SECTION]", sName.ToLower());
            ViewData["Breadcrumb"] = saBreadcrumb;

            if (User.Identity.IsAuthenticated)
            {
                MembershipUser mu = Membership.GetUser(User.Identity.Name);
                ProfileBase pb = ProfileBase.Create(mu.UserName);
                ViewData["Firstname"] = pb["FirstName"];
                ViewData["Lastname"] = pb["LastName"];
                ViewData["Mail"] = mu.Email;
            }

            int sectionId = (section != null) ? section.ID : 0;
            ViewData["Section"] = new SelectList(sr.GetSections(), "ID", "Section", sectionId);
            return View("Contact");
        }

        [CaptchaValidator]
        [HttpPost]
        [ValidateAntiForgeryToken()]
        public ActionResult Index(string systemName, FormCollection fc, bool captchaValid)
        {
            tSite_Section section = null;
            string sName = string.Empty;
            if (systemName != null)
            {
                section = sr.GetSectionsBySystemName(systemName);
                if (section != null)
                {
                    sName = section.Section;
                }
            }

            ViewData["PageDescription"] = Resources.Contact_Index_Description.Replace("[SECTION]", sName.ToLower());
            ViewData["PageTitle"] = Resources.Contact_Index_Title.Replace("[SECTION]", sName.ToLower());

            string[] saBreadcrumb = new String[2];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = Resources.Contact_Index_Breadcrumb.Replace("[SECTION]", sName.ToLower());
            ViewData["Breadcrumb"] = saBreadcrumb;

            string email;
            string firstName;
            string lastName;
            if (User.Identity.IsAuthenticated)
            {
                MembershipUser mu = Membership.GetUser(User.Identity.Name);
                ProfileBase pb = ProfileBase.Create(mu.UserName);
                firstName = pb["FirstName"].ToString();
                lastName = pb["LastName"].ToString();
                email = mu.Email;
                ViewData["Firstname"] = firstName;
                ViewData["Lastname"] = lastName;
                ViewData["Mail"] = email;
            }
            else
            {
                firstName = fc["firstname"].ToString();
                lastName = fc["lastname"].ToString();
                email = fc["email"].ToString();
            }

            int sectionId = (section != null) ? section.ID : 0;
            ViewData["Section"] = new SelectList(sr.GetSections(), "ID", "Section", sectionId);

            if (ValidateContact(fc, captchaValid))
            {
                string mailTo = sr.GetSectionsById(Convert.ToInt32(fc["section"])).Email;
                Mail.SendMail(mailTo
                    , fc["subject"]
                    , fc["Message"]
                    , email
                    , firstName + " " + lastName);

                ViewData["ValidationMessage"] = Resources.Profil_Contact_Validation.Replace("[USERNAME]", firstName);
                return View("Validation");
            }
            return View("Contact");
        }
        #endregion

        #region Methodes
        private bool ValidateContact(FormCollection fc, bool captchaValid)
        {
            if (!User.Identity.IsAuthenticated)
            {
                ModelState.SetModelValue("firstname", ValueProvider.GetValue("firstname"));
                ModelState.SetModelValue("lastname", ValueProvider.GetValue("lastname"));
                ModelState.SetModelValue("email", ValueProvider.GetValue("email"));
            }
            ModelState.SetModelValue("subject", ValueProvider.GetValue("subject"));
            ModelState.SetModelValue("message", ValueProvider.GetValue("message"));

            if (String.IsNullOrEmpty(fc["firstname"]) && !User.Identity.IsAuthenticated)
            {
                ModelState.AddModelError("firstname", Resources.Contact_Index_Error_Firstname);
            }

            if (String.IsNullOrEmpty(fc["lastname"]) && !User.Identity.IsAuthenticated)
            {
                ModelState.AddModelError("lastname", Resources.Contact_Index_Error_Lastname);
            }

            if ((String.IsNullOrEmpty(fc["email"]) || !Validation.IsEmail(fc["email"])) && !User.Identity.IsAuthenticated)
            {
                ModelState.AddModelError("email", Resources.Contact_Index_Error_Email);
            }

            if (String.IsNullOrEmpty(fc["subject"]))
            {
                ModelState.AddModelError("subject", Resources.Contact_Index_Error_Subject);
            }

            if (String.IsNullOrEmpty(fc["message"]))
            {
                ModelState.AddModelError("message", Resources.Contact_Index_Error_Message);
            }

            if (!User.Identity.IsAuthenticated)
            {
                if (!captchaValid)
                {
                    ModelState.AddModelError(string.Empty, Resources.Contact_Index_Error_Captcha);
                }
            }
            
            return ModelState.IsValid;
        }
        #endregion
    }
}
